package net.b521.petshop.service.impl;


import net.b521.petshop.dao.SellerMapper;
import net.b521.petshop.dao.UserMapper;
import net.b521.petshop.dao.model.Seller;
import net.b521.petshop.dao.model.SellerExample;
import net.b521.petshop.dao.model.User;
import net.b521.petshop.dao.model.UserExample;
import net.b521.petshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SellerMapper sellerMapper;

    @Override
    public User findById(int id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> findAll() {
        UserExample userExample = new UserExample();
        return userMapper.selectByExample(userExample);
    }


    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int create(User user) {
        int i = userMapper.insertSelective(user);
        return i;
        // return userDao.save(user).getId();
    }

    @Override
    public void delById(int id) {
        // userDao.delete(id);
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据用户名查询
     *
     * @param username
     * @return
     */
    @Override
    public List<User> findByUsername(String username) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        return userMapper.selectByExample(userExample);
    }

    /**
     * 检查登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User checkLogin(String username, String password) {
        // UserExample userExample = new UserExample();
        // userExample.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);
        // User user = userMapper.selectByExample(userExample).get(0);

        // User user = userMapper.findByUsernameAndPassword(username, password);
        // if (user == null) {
        //     throw new LoginException("登录失败!用户名或者密码错误");
        // }
        return userMapper.findByUsernameAndPassword(username, password);
        // return user;
        // return userDao.findByUsernameAndPassword(username, password);
    }

    @Override
    public Seller saveSeller(User user) {
        SellerExample sellerExample = new SellerExample();
        sellerExample.createCriteria()
                .andUserIdEqualTo(user.getId());
        List<Seller> sellers = sellerMapper.selectByExample(sellerExample);
        return sellers.get(0);
    }

}
